package com.easipass.framework.eirframeworkcoredsl;

import java.util.HashMap;
import java.util.Map;

public class ParseException extends RuntimeException {

    protected String expressionString;

    protected int position;

    protected DSLMessage message;

    protected Object[] inserts;

    public ParseException(String expressionString, int position, DSLMessage message, Object... inserts) {
        super(message.formatMessage(position, inserts));
        this.position = position;
        this.message = message;
        this.inserts = inserts;
        this.expressionString = expressionString;
    }

    @Override
    public String getMessage() {
        StringBuilder s = new StringBuilder();
        if (message != null) {
            s.append(message.formatMessage(position, inserts));
        } else {
            s.append(super.getMessage());
        }
        if (expressionString != null && expressionString.length() > 0) {
            s.append("\n").append(expressionString).append("\n");
        }
        if (position >= 0) {
            for (int i = 0; i < position; i++) {
                s.append(' ');
            }
            s.append("^\n");
        }
        return s.toString();
    }

    public DSLMessage getMessageCode() {
        return this.message;
    }

    public Object[] getInserts() {
        return inserts;
    }

    public final String getExpressionString() {
        return this.expressionString;
    }

    public final int getPosition() {
        return position;
    }

    public Map<String, Object> toExceptionDescriptor() {
        Map<String, Object> descriptor = new HashMap<>();
        String text = null;
        if (message != null) {
            text = message.formatMessage(position, inserts);
        } else {
            text = super.getMessage();
        }
        descriptor.put("message", text);
        descriptor.put("position", position);
        return descriptor;
    }
}
